package com.cn.jdia.tas.controller;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.joda.time.DateTime;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.cn.jdia.tas.context.SpringContextUtils;
import com.cn.jdia.tas.model.T_attrecord;
import com.cn.jdia.tas.service.IAttrecordService;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

@Controller
@RequestMapping("/control")
public class DetailRecordController {

	@Resource
	private IAttrecordService service = null;
		
	@RequestMapping("/detail")
	public String getDailyData(HttpServletRequest request, HttpServletResponse response) throws IOException {
		
		response.setHeader("Access-Control-Allow-Origin", "*");
		response.setContentType("text/html;charset=utf-8");
		PrintWriter out = response.getWriter();
		
		String data = request.getParameter("data");

		Gson gson = new Gson();
		Map<String, String> map = gson.fromJson(data, new TypeToken<Map<String, String>>() {
		}.getType());

		String id=map.get("id");
		String start = map.get("start");
		String end = map.get("end");
		
		DateTimeFormatter format = DateTimeFormat.forPattern("YYYY-MM-dd");
		DateTime edDt = DateTime.parse(end, format).plusDays(1);

		String mySt = start.replaceAll("-", "");
		String myEd = edDt.toString("YYYYMMdd");
		
//		ClassPathXmlApplicationContext w_context = new ClassPathXmlApplicationContext("spring-mybatis.xml");
//		service = (IAttrecordService) w_context.getBean("attrecordService");
		
		service=(IAttrecordService)SpringContextUtils.getContext().getBean("attrecordService");
		
		List<T_attrecord> attrecordsByDate = service.getDetailAttrecords(id,mySt, myEd);
		
		String date;
		String time;
		String type;
		String machine;
		
		List<Map<String,String>> list=new ArrayList<>();
		
		for (T_attrecord acc : attrecordsByDate) {
			date=acc.getCheckdate();
			time=acc.getChecktime();
			type=acc.getChecktype();
			machine=acc.getAttmachinename();
			
			Map<String,String> r_map=new HashMap<>();
			r_map.put("date", date);
			r_map.put("time", time);
			r_map.put("type", type);
			r_map.put("machine", machine);
			
			list.add(r_map);			
		}
		
		
		String retDate = gson.toJson(list);
		System.out.println(retDate);

		out.write(retDate);
		out.flush();
		out.close();
		return null;
	}
}
